#extension GL_OES_EGL_image_external : require
precision mediump float;
uniform samplerExternalOES texture;
varying vec2 v_TexCoordinate;
uniform float scale, aspect, g_lat, g_lon;
const float PI = 3.1415926535897932384626433832795;
vec2 caltexture(vec2 coords, float clat, float clng) {
    float p = length(coords);
    float d = 0.95;
    float dx = 0.0;
    float dy = 0.0;
    float c = 2.0 * atan( p, d);
    float lat = asin(cos(c)*sin(clat) + coords.y*sin(c)*cos(clat)/p);
    float lon = clng + atan(coords.x*sin(c), p*cos(clat)*cos(c)-coords.y*sin(c)*sin(clat));
    if(lat < 0.0){
        return vec2(0.0,0.0);
    }
    return vec2( 0.5-d/2.0*cos(lat)*cos(lon)-dx, 0.5-d/2.0*cos(lat)*sin(lon)-dy);
}
void main () {
    vec2 scaledCoords;
    vec2 texCoords;
    float cla = (g_lat/180.0) * PI;
    float lon = (g_lon/180.0) * PI;
    scaledCoords = v_TexCoordinate * vec2(scale * aspect, scale);
    texCoords = caltexture(scaledCoords, cla, lon);
    gl_FragColor = texture2D(texture, texCoords);;
}